package com.gilstar.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.gilstar.common.Constant;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import codeartist.ibatis.SQLManager;
import codeartist.json.JSONHandler;

public class GilstarServlet extends HttpServlet 
{
	private static Logger log = LoggerFactory.getLogger(GilstarServlet.class);
	
	protected JSONHandler jsonHandler;
	protected SQLManager sqlManager = SQLManager.getInstance();
	
	protected ServletContext scx;
	protected Hex h;
	
	protected String path;
	
	
	@Override
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);
		
		//initialize (setting upload path, init json handler)
		scx = getServletContext();
		path = scx.getRealPath("/") + Constant.UPLOAD_PATH;
		
		jsonHandler = new JSONHandler();
		
		h = new Hex();
	}
	@Deprecated
	@Override
	public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
	{
		try
		{
			JSONObject req = jsonHandler.read(request);
			log.debug("req : [" + req + "]");
			
			String mname = req.getString(Constant.REQ);
			
			if(StringUtils.equals(mname, Constant.METHOD_NAME_REGISTER_PERFORMANCE))
			{
				String title = req.getString(Constant.TITLE);
				String artist = req.optString(Constant.ARTIST);
				String category = req.getString(Constant.CATEGORY);
				float latitude = Float.parseFloat(req.optString(Constant.LATITUDE));
				float longitude = Float.parseFloat(req.optString(Constant.LONGITUDE));
				String time = req.getString(Constant.TIME);
				String content = req.optString(Constant.CONTENT);
				String email = req.getString(Constant.EMAIL);
				String sns_url = req.optString(Constant.SNS_URL);
				
				//data 검증...
				
				if(StringUtils.isBlank(title) || StringUtils.length(title) > 200)
				{
					
					return;
				}
				
			}
			else if(StringUtils.equals(mname, "test"))
			{
				List rList = sqlManager.select("Performance.test");
				jsonHandler.flush(response, JSONHandler.SERVER_EXECUTION_CODE, Constant.EMPTY, ArrayUtils.toString(rList));
			}
		}
		catch (Exception e) 
		{
			log.error("exception : {}", e.getMessage());
			jsonHandler.flush(response, JSONHandler.SERVER_ERROR_CODE, Constant.ERROR_MESSAGE, null);
		}
	}
}
